<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>

            <!-- active:设置当前激活步骤(number) -->
            <el-steps :space="500" :active="active-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <!-- el-tabs中的v-model会将指定切换的el-tab-pane的name进行存储  -->
            <el-form :model="addForm" :rules="addFormrRules" ref="addFormRef"
                label-width="100px" label-position="top">

                <!-- before-leave：切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
                <el-tabs tab-position="left" v-model="active" :before-leave="beforeTabLeave" @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model.number="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_number">
                            <el-input v-model.number="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_weight">
                            <el-input v-model.number="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>

                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="props" clearable
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>

                    </el-tab-pane>

                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>

                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>

                    <el-tab-pane label="商品图片" name="3">
                        <!-- 不能使用相对路径,如果使用相对路径,那么浏览器会自动将当前浏览器当的路径与当前相对路径进行拼接 -->
                        <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :headers="headerObj"
                            :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess"
                            list-type="picture">

                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>

                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>

                        <el-button @click="addGood" type="primary">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>

            </el-form>

        </el-card>

        <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
            <img :src="previewPath" alt="" width="100%">
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Add',

  data () {
    return {
      active: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [], // 商品分类id
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormrRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },

      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      cateList: [],

      manyTableData: [],
      onlyTableData: [],

      // 上传图片没有调用axios,因此没有走axios的拦截器,因此没有添加到header
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      dialogVisible: false
    }
  },

  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },

  created () {
    this.getCateList()
  },

  methods: {
    async getCateList () {
      const { data, meta } = await this.$http.goodsList.getGoodsCategories()
      if (meta.status === 200) {
        this.cateList = data
      }
    },

    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // 为基本信息和商品参数直接进行切换,调用的钩子
    // activeName:el-tabs切换的el-tab-plane名字,oldActiveName:el-tabs离开的el-tab-plane名字
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false // return false之后,el-tabs就不会出发切换效果
      }
    },

    // 点击el-tabs进行切换
    async tabClicked () {
      if (this.active === '1') {
        const { data, meta } = await this.$http.goodsList.getCategoriesAttrList(this.cateId, { params: { sel: 'many' } })
        if (meta.status === 200) {
          data.forEach(item => {
            // 必须要校验attr_vals是否为"",因为"".split('')返回的[''],此时数组是有长度的有值的
            item.attr_vals = (item.attr_vals.length === 0 ? [] : item.attr_vals.split(' '))
          })

          this.manyTableData = data
        } else {
          this.$message.error('获取动态属性失败')
        }
      } else if (this.active === '2') {
        const { data, meta } = await this.$http.goodsList.getCategoriesAttrList(this.cateId, { params: { sel: 'only' } })
        if (meta.status === 200) {
          this.onlyTableData = data
        } else {
          this.$message.error('获取动态属性失败')
        }
      }
    },

    // 文件上传相关事件回调函数
    // 文件列表移除文件时的钩子
    handleRemove (file, fileList) {
      const { response: { data, meta } } = file

      this.addForm.pics = this.addForm.pics.filter((item) => {
        return item.pic !== data.tmp_path
      })
    },

    // 处理图片预览效果
    handlePreview (file) {
      const { response: { data } } = file

      this.previewPath = data.url // 图片预览要使用绝对路径

      this.dialogVisible = true
    },

    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },

    // 图片上传成功后执行的函数
    handleSuccess (response, file, fileList) {
      this.addForm.pics.push({ pic: response.data.tmp_path })
    },

    addGood () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          this.addForm.goods_cat = this.addForm.goods_cat.join(',')

          const manyData = this.manyTableData.map(item => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
          })

          const onlyData = this.onlyTableData.map(item => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
          })

          manyData.forEach(item => {
            this.addForm.attrs.push(item)
          })

          onlyData.forEach(item => {
            this.addForm.attrs.push(item)
          })

          const { data, meta } = await this.$http.goodsList.addGood(this.addForm)
          if (meta.status === 201) {
            this.$message.success('添加商品成功')
            this.$router.push('/goods')
          } else {
            this.$message.error('添加商品失败')
          }
        } else {
          this.$message.error('请填写必要的字段')
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
    .el-steps {
        margin: 20px;
    }
    /deep/ .el-step__title{
        font-size: 13px;
    }
    .el-checkbox {
        margin: 0 10px 0 0 !important;
    }
    .quill-editor {
        margin: 20px 0;
    }
</style>
